package net.forsalemall.android;

import org.json.JSONObject;

import com.google.android.c2dm.C2DMessaging;
import com.google.android.c2dm.GCMConstants;
import com.google.android.c2dm.GCMUtils;
import com.markupartist.android.widget.ActionBar;
import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.TextDrawable;
import com.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends Activity {

	private String deviceDetails;

	private Button regiButton;
	private Button serviceButton;
	private Button dealButton;

	private ActionBar actionBar;

	private OnSharedPreferenceChangeListener ospcl;
	private SharedPreferences sharedPreference;

	private String country;
	private boolean isRegister;

	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.home);
			try {
				if (GCMUtils.getRegId(this) == null) {
					C2DMessaging.register(this,GCMConstants.SENDER_ID);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			deviceDetails = HttpUtils.getDeviceDetails(false,
					Utils.getDeviceId(HomeActivity.this));

			sharedPreference = PreferenceManager
					.getDefaultSharedPreferences(this);
			ospcl = new OnSharedPreferenceChangeListener() {

				public void onSharedPreferenceChanged(
						SharedPreferences sharedPreferences, String key) {
					try {
						Log.i("DREG", "KEY=" + key);
						if (Constants.KEY_REGISTER_NOTIFICATION.equals(key)) {
							if (!isFinishing()) {
								deviceDetails = HttpUtils.getDeviceDetails(
										false,
										Utils.getDeviceId(HomeActivity.this));

								if (isRegister) {
									runOnUiThread(new Runnable() {
										public void run() {
											try {
												startProcess();
												
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									});
								} else {
									runOnUiThread(new Runnable() {
										public void run() {
											try {
												startProcess();
												if (isRegister) {
													Utils.showAlertMessage(
															HomeActivity.this,
															null,
															getString(R.string.registration_complete_message));
												}
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									});
								}
							}
						} else if (Constants.KEY_COUNTRY.equals(key)) {
							country = sharedPreference.getString(
									Constants.KEY_COUNTRY,
									Constants.COUNTRY_KUWAIT);
							runOnUiThread(new Runnable() {
								public void run() {
									try {
										if (Constants.COUNTRY_UAE
												.equals(country)) {
											actionBar
													.setTitle(R.string.home_title_uae);
										} else {
											actionBar
													.setTitle(R.string.home_title_kw);
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							});

							Log.i("DREG", "COUNTRY=" + country);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			sharedPreference.registerOnSharedPreferenceChangeListener(ospcl);
			actionBar = (ActionBar) findViewById(R.id.actionbar);
//			actionBar.setHomeLogo(R.drawable.home_logo);

			actionBar.setTitle(R.string.app_name);

			regiButton = (Button) findViewById(R.id.button_register);

			regiButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					checkRegStatus();
				}
			});
			findViewById(R.id.button_for_sale).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							Intent intent = new Intent(HomeActivity.this,
									SuperCategoriesActivity.class);
							String countryCode = Constants.COUNTRY_UAE
									.equals(country) ? Constants.COUNTRY_CODE_UAE
									: Constants.COUNTRY_CODE_KUWAIT;
							intent.putExtra(Constants.KEY_COUNTRY_CODE,
									countryCode);
							intent.putExtra(Constants.KEY_CATEGORY_TYPE,
									Constants.TYPE_NORMAL_CAT);
							intent.putExtra(Constants.KEY_AD_TYPE,
									Constants.TYPE_NORMAL_AD);
							startActivity(intent);
						}
					});
			serviceButton = (Button)findViewById(R.id.button_service);
			serviceButton.setVisibility(Constants.isServiceDisabled()?View.GONE:View.VISIBLE);
			serviceButton.setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							Intent intent = new Intent(HomeActivity.this,
									SuperCategoriesActivity.class);
							String countryCode = Constants.COUNTRY_UAE
									.equals(country) ? Constants.COUNTRY_CODE_UAE
									: Constants.COUNTRY_CODE_KUWAIT;
							intent.putExtra(Constants.KEY_COUNTRY_CODE,
									countryCode);
							intent.putExtra(Constants.KEY_CATEGORY_TYPE,
									Constants.TYPE_FEATURE_CAT);
							intent.putExtra(Constants.KEY_AD_TYPE,
									Constants.TYPE_FEATURE_AD);
							startActivity(intent);
						}
					});
			findViewById(R.id.button_latest).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							Intent intent = new Intent(HomeActivity.this,
									AdsByTimeActivity.class);
							String countryCode = Constants.COUNTRY_UAE
									.equals(country) ? Constants.COUNTRY_CODE_UAE
									: Constants.COUNTRY_CODE_KUWAIT;
							intent.putExtra(Constants.KEY_COUNTRY_CODE,
									countryCode);
							intent.putExtra(Constants.KEY_CATEGORY_ID, 0);
							intent.putExtra(Constants.KEY_CATEGORY_NAME,
									getString(R.string.latest_100_ads));
							startActivity(intent);
						}
					});
			dealButton = (Button)findViewById(R.id.button_deals);
			dealButton.setVisibility(Constants.isDealDisabled()?View.GONE:View.VISIBLE);
			dealButton.setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							Intent intent = new Intent(HomeActivity.this,
									DealCategoriesActivity.class);
							String countryCode = Constants.COUNTRY_UAE
									.equals(country) ? Constants.COUNTRY_CODE_UAE
									: Constants.COUNTRY_CODE_KUWAIT;
							intent.putExtra(Constants.KEY_COUNTRY_CODE,
									countryCode);
							startActivity(intent);
						}
					});
			findViewById(R.id.button_settings).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							Intent intent = new Intent(HomeActivity.this,
									SettingsActivity.class);
							intent.putExtra(Constants.KEY_IS_REGISTER,
									isRegister);
							startActivity(intent);
						}
					});
			findViewById(R.id.button_post_ad).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							try {
								if (isRegister) {
									JSONObject jo = new JSONObject(
											deviceDetails);
									Intent intent = new Intent(
											HomeActivity.this, UploadAds.class);
									String countryCode = Constants.COUNTRY_UAE
											.equals(country) ? Constants.COUNTRY_CODE_UAE
											: Constants.COUNTRY_CODE_KUWAIT;
									intent.putExtra(Constants.KEY_COUNTRY_CODE,
											countryCode);
									intent.putExtra(Constants.KEY_PHONE_NO,
											jo.getString("phone_no"));
									startActivity(intent);
								} else {
									buildAlertMessageUnregister();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
			findViewById(R.id.button_favorites).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							if (isRegister) {
								Intent intent = new Intent(HomeActivity.this,
										AdsByFavoritesActivity.class);
								String countryCode = Constants.COUNTRY_UAE
										.equals(country) ? Constants.COUNTRY_CODE_UAE
										: Constants.COUNTRY_CODE_KUWAIT;
								intent.putExtra(Constants.KEY_COUNTRY_CODE,
										countryCode);
								intent.putExtra(Constants.KEY_CATEGORY_ID, 0);
								intent.putExtra(Constants.KEY_CATEGORY_NAME,
										getString(R.string.title_favorites));
								startActivity(intent);

							} else {
								buildAlertMessageUnregister();
							}
						}
					});
			findViewById(R.id.button_my_ads).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							if (isRegister) {
								Intent intent = new Intent(HomeActivity.this,
										AdsByMeActivity.class);
								String countryCode = Constants.COUNTRY_UAE
										.equals(country) ? Constants.COUNTRY_CODE_UAE
										: Constants.COUNTRY_CODE_KUWAIT;
								intent.putExtra(Constants.KEY_COUNTRY_CODE,
										countryCode);
								intent.putExtra(Constants.KEY_CATEGORY_ID, 0);
								intent.putExtra(Constants.KEY_CATEGORY_NAME,
										getString(R.string.title_my_ads));
								startActivity(intent);

							} else {
								buildAlertMessageUnregister();
							}
						}
					});
			findViewById(R.id.button_contact_us).setOnClickListener(
					new View.OnClickListener() {

						public void onClick(View v) {
							try {
								String phoneNo = "";
								if (isRegister) {
									JSONObject jo = new JSONObject(
											deviceDetails);
									phoneNo = jo.getString("phone_no");

								}
								Intent intent = new Intent(HomeActivity.this,
										ContactUs.class);
								String countryCode = Constants.COUNTRY_UAE
										.equals(country) ? Constants.COUNTRY_CODE_UAE
										: Constants.COUNTRY_CODE_KUWAIT;
								intent.putExtra(Constants.KEY_COUNTRY_CODE,
										countryCode);
								intent.putExtra(Constants.KEY_PHONE_NO, phoneNo);
								startActivity(intent);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
			startProcess();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void finish() {
		buildAlertMessageExit();
	}

	private void buildAlertMessageUnregister() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.registerd_user_feature))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.yes),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								checkRegStatus();
							}
						})
				.setNegativeButton(getString(R.string.no),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	private void buildAlertMessageExit() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.exit_confirmation))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.yes),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								exit();
							}
						})
				.setNegativeButton(getString(R.string.no),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	private void exit() {
		try {
			super.finish();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startProcess() throws Exception {
		JSONObject jo = new JSONObject(deviceDetails);
		isRegister = (jo.getInt("status") == 1);
		if (isRegister) {
			regiButton.setEnabled(false);
		} else {
			regiButton.setEnabled(true);
		}
		country = sharedPreference.getString(Constants.KEY_COUNTRY, null);
		if (country == null) {
			setCountry();
		} else {
			if (Constants.COUNTRY_UAE.equals(country)) {
				actionBar.setTitle(R.string.home_title_uae);
			} else {
				actionBar.setTitle(R.string.home_title_kw);
			}
		}
	}

	private void setCountry() {
		try {
			final Dialog dialog = new Dialog(this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(LayoutInflater.from(this).inflate(
					R.layout.country_dialog, null));
			dialog.getWindow().setLayout(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			dialog.setCancelable(false);

			Button okButton = (Button) dialog.findViewById(R.id.button_ok);
			final RadioButton optionKuwait = (RadioButton) dialog
					.findViewById(R.id.radio_kuwait);
			final RadioButton optionUAE = (RadioButton) dialog
					.findViewById(R.id.radio_uae);
			if (Constants.COUNTRY_UAE.equals(country)) {
				optionKuwait.setChecked(false);
				optionUAE.setChecked(true);
			} else {
				optionUAE.setChecked(false);
				optionKuwait.setChecked(true);
			}
			okButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					if (optionUAE.isChecked()) {
						sharedPreference
								.edit()
								.putString(Constants.KEY_COUNTRY,
										Constants.COUNTRY_UAE).commit();
					} else {
						sharedPreference
								.edit()
								.putString(Constants.KEY_COUNTRY,
										Constants.COUNTRY_KUWAIT).commit();
					}
					dialog.dismiss();
				}
			});
			dialog.show();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void checkRegStatus() {
		try {
			final String sentPhoneNo = sharedPreference.getString(
					Constants.KEY_SMS_SENT_TO, null);
			if (sentPhoneNo != null
					&& sentPhoneNo.length() >= Math.min(
							Constants.NUMBER_OF_PHONE_DIGIT_UAE,
							Constants.NUMBER_OF_PHONE_DIGIT_KUWAIT)) {
				final Dialog dialog = new Dialog(this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(LayoutInflater.from(this).inflate(
						R.layout.reg_options_dialog, null));
				dialog.getWindow().setLayout(LayoutParams.FILL_PARENT,
						LayoutParams.WRAP_CONTENT);
				dialog.setCancelable(true);

				Button okButton = (Button) dialog.findViewById(R.id.button_ok);
				final RadioButton optionHaveKey = (RadioButton) dialog
						.findViewById(R.id.radio_i_have_key);
				final RadioButton optionSendMeKey = (RadioButton) dialog
						.findViewById(R.id.radio_send_me_key);
				if (Constants.COUNTRY_UAE.equals(country)) {
					optionHaveKey.setChecked(false);
					optionSendMeKey.setChecked(true);
				} else {
					optionSendMeKey.setChecked(false);
					optionHaveKey.setChecked(true);
				}
				okButton.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						dialog.dismiss();
						if (optionSendMeKey.isChecked()) {
							register();
						} else {
							submitKeyOption(sentPhoneNo);
						}

					}
				});
				dialog.show();
			} else {
				register();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void submitKeyOption(final String phoneNo) {
		try {
			final Dialog dialog = new Dialog(this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(LayoutInflater.from(this).inflate(
					R.layout.submit_key_dialog, null));
			dialog.getWindow().setLayout(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			Button submitButton = (Button) dialog
					.findViewById(R.id.button_submit);
			Button cancelButton = (Button) dialog
					.findViewById(R.id.button_cancel);
			final TextView regkeyView = (TextView) dialog
					.findViewById(R.id.reg_key_fields);
			submitButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					final String typedKey = regkeyView.getText().toString();
					final String key = sharedPreference.getString(
							Constants.KEY_SMS_CODE, null);
					if ((key != null) && (key.equals(typedKey))) {
						dialog.dismiss();
						register(phoneNo);
					} else {
						Utils.showAlertMessage(HomeActivity.this, null,
								getString(R.string.reg_key_not_match));
					}
				}
			});
			cancelButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void register() {
		try {
			final String phoneNo = Utils.getPhoneNumber(this);
			final Dialog dialog = new Dialog(this);
			final int phoneDigit = Constants.COUNTRY_KUWAIT.equals(country) ? Constants.NUMBER_OF_PHONE_DIGIT_KUWAIT
					: Constants.NUMBER_OF_PHONE_DIGIT_UAE;
			final String phonePrefix = Constants.COUNTRY_KUWAIT.equals(country) ? Constants.PHONE_CODE_KUWAIT
					: Constants.PHONE_CODE_UAE;

			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(LayoutInflater.from(this).inflate(
					R.layout.register_dialog, null));
			dialog.getWindow().setLayout(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			TextView termsAndCondField = (TextView) dialog
					.findViewById(R.id.terms_and_condition_fields);
			termsAndCondField.setText(Constants.getTermsAndConditions());
			Button registerButton = (Button) dialog
					.findViewById(R.id.button_register);
			Button cancelButton = (Button) dialog
					.findViewById(R.id.button_cancel);
			final TextView phoneNoView = (TextView) dialog
					.findViewById(R.id.phone_no_fields);
			TextDrawable td = new TextDrawable(phonePrefix + "-");
			td.setTextSize(phoneNoView.getTextSize());
			// td.getBounds().

			phoneNoView.setCompoundDrawablesWithIntrinsicBounds(td, null, null,
					null);
			if (phoneNo != null) {
				phoneNoView.setVisibility(View.GONE);
			} else {
				InputFilter[] FilterArray = new InputFilter[1];
				FilterArray[0] = new InputFilter.LengthFilter(phoneDigit);
				phoneNoView.setFilters(FilterArray);
			}
			registerButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					if (phoneNo != null) {
						register(phoneNo);
						dialog.dismiss();
					} else if (phoneNoView.getText().length() == phoneDigit) {
						sendSMS(phonePrefix + phoneNoView.getText().toString());
						dialog.dismiss();
					} else {
						Utils.showAlertMessage(HomeActivity.this, null,
								getString(R.string.enter_valid_phone_no));
					}
				}
			});
			cancelButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void sendSMS(String phoneNo) {
		try {
			String key = Utils.generateKey(Constants.SMS_CODE_LENGTH);
			sharedPreference.edit().putString(Constants.KEY_SMS_CODE, key)
					.commit();
			sharedPreference.edit()
					.putString(Constants.KEY_SMS_SENT_TO, phoneNo).commit();
			sendSMS(phoneNo,
					String.format(getString(R.string.forsalemall_reg_key), key));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void sendSMS(String phoneNo, String message) {
		try {
			Log.i("DREG", "MESSAGE=" + message);
			SmsManager sms = SmsManager.getDefault();
			sms.sendTextMessage(phoneNo, null, message, null, null);
			Toast.makeText(this,
					getString(R.string.registration_processing_message),
					Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			Utils.showAlertMessage(this, null, e.getMessage());
			e.printStackTrace();
		}
	}

	private void register(final String phoneNo) {
		try {
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;

				protected void onPreExecute() {
					try {
						progressDialog = Utils.getProgressDialog(
								HomeActivity.this, null,
								getString(R.string.loading));
						progressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected String doInBackground(String... arg0) {
					try {
						deviceDetails = HttpUtils.registerDevice(
								Utils.getDeviceId(HomeActivity.this), phoneNo);
						sharedPreference.edit()
								.putString(Constants.KEY_SMS_CODE, null)
								.commit();
						sharedPreference.edit()
								.putString(Constants.KEY_SMS_SENT_TO, null)
								.commit();
						sharedPreference
								.edit()
								.putLong(Constants.KEY_REGISTER_NOTIFICATION,
										System.currentTimeMillis()).commit();
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						// startProcess();
						progressDialog.dismiss();

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
